import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:citiesocial/bases/strings.dart';
import 'dart:async';
import 'package:flutter/foundation.dart' show SynchronousFuture;

class BaseMaterialApp extends MaterialApp {
  static const _supported_locales = const [
    const Locale('en', 'US'),
    const Locale('zh', 'CN'),
  ];

  BaseMaterialApp({
    Key key,
    navigatorKey,
    home,
    routes: const <String, WidgetBuilder>{},
    initialRoute,
    onGenerateRoute,
    onUnknownRoute,
    navigatorObservers: const <NavigatorObserver>[],
    builder,
    title: '',
    onGenerateTitle,
    color,
    theme,
    locale,
    localizationsDelegates,
    localeResolutionCallback,
    supportedLocales: _supported_locales,
    debugShowMaterialGrid: false,
    showPerformanceOverlay: false,
    checkerboardRasterCacheImages: false,
    checkerboardOffscreenLayers: false,
    showSemanticsDebugger: false,
    debugShowCheckedModeBanner: true,
  }) : super(
            key: key,
            navigatorKey: navigatorKey,
            home: home,
            routes: routes,
            initialRoute: initialRoute,
            onGenerateRoute: onGenerateRoute,
            onUnknownRoute: onUnknownRoute,
            navigatorObservers: navigatorObservers,
            builder: builder,
            title: title,
            onGenerateTitle: onGenerateTitle,
            color: color,
            theme: theme,
            locale: locale,
            localizationsDelegates: localizationsDelegates,
            localeResolutionCallback: localeResolutionCallback,
            supportedLocales: supportedLocales,
            debugShowMaterialGrid: debugShowMaterialGrid,
            showPerformanceOverlay: showPerformanceOverlay,
            checkerboardRasterCacheImages: checkerboardRasterCacheImages,
            checkerboardOffscreenLayers: checkerboardOffscreenLayers,
            showSemanticsDebugger: showSemanticsDebugger,
            debugShowCheckedModeBanner: debugShowCheckedModeBanner);

  @override
  Iterable<LocalizationsDelegate> get localizationsDelegates {
    return const [
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      TextsDelegate.delegate,
    ];
  }

  @override
  Iterable<Locale> get supportedLocales => _supported_locales;
}

abstract class BaseStatefulWidget extends StatefulWidget {
  String getContextString(BuildContext context, String key) =>
      Texts().getWithContext(context, key);
  String getString(String key) => Texts().getString(key);

  ///与原生交互通道
  static const platform = const MethodChannel('cn.dujc.citiesocial');

  ///获取推送设备id
  Future<String> getDeviceId() async =>
      await platform.invokeMethod('getDeviceId');
}

abstract class BaseState<T extends StatefulWidget> extends State<T> {
  String getContextString(BuildContext context, String key) =>
      Texts().getWithContext(context, key);
  String getString(String key) => Texts().getString(key);

  ///与原生交互通道
  static const platform = const MethodChannel('cn.dujc.citiesocial');

  ///获取推送设备id
  Future<String> getDeviceId() async =>
      await platform.invokeMethod('getDeviceId');
}

abstract class BaseStatelessWidget extends StatelessWidget {
  String getContextString(BuildContext context, String key) =>
      Texts().getWithContext(context, key);
  String getString(String key) => Texts().getString(key);

  ///与原生交互通道
  static const platform = const MethodChannel('cn.dujc.citiesocial');

  ///获取推送设备id
  Future<String> getDeviceId() async =>
      await platform.invokeMethod('getDeviceId');
}

class Texts {
  static const String _default_language = 'zh';
  static const support_language = ['en', _default_language];

  Texts._internal();

  static final Texts instance = Texts._internal();

  factory Texts() {
    return instance;
  }

  String languageCode = _default_language;

  Texts initLanguageContext(BuildContext context) {
    if (context != null)
      languageCode =
          Localizations.localeOf(context, nullOk: true)?.languageCode;
    if (languageCode == null) languageCode = _default_language;
    return this;
  }

  Texts initLanguageString(String languageCode) {
    if (languageCode != null && languageCode.isNotEmpty)
      this.languageCode = languageCode;
    return this;
  }

  Texts initLanguageLocale(Locale locale) {
    return initLanguageString(locale?.languageCode);
  }

  String getWithContext(BuildContext context, String key) {
    initLanguageContext(context);
    return getString(key);
  }

  String getString(String key) {
    var texts = Strings.localizedValues[languageCode];
    if (texts == null || texts.length == 0) //若是取不到这个map，或者取到了map但值为空，则取默认的map
      texts = Strings.localizedValues[_default_language];
    var result = texts[key];
    if (result == null) result = ''; //若是取到了map，但没取到对应的key，将返回空字符串
    return result;
  }
}

class TextsDelegate extends LocalizationsDelegate<Texts> {
  const TextsDelegate();

  static const TextsDelegate delegate = const TextsDelegate();

  @override
  bool isSupported(Locale locale) =>
      Texts.support_language.contains(locale.languageCode);

  @override
  Future<Texts> load(Locale locale) {
    return SynchronousFuture<Texts>(Texts().initLanguageLocale(locale));
  }

  @override
  bool shouldReload(TextsDelegate old) => (old != this);
}
